<?php

namespace core\lib;

use core\lib\DingDing;

/**
 * 错误类
 */
class Exception extends \Exception
{
    // 默认code
    public $code = 500;
    // 默认消息
    public $msg = '系统级别错误';

    /**
     * 构造函数，接收一个关联数组
     * @param array $params 关联数组只应包含code、msg，且不应该是空值
     */
    public function __construct($params = [])
    {
        if (!is_array($params)) {
            return;
        }
        if (array_key_exists('code', $params)) {
            $this->code = $params['code'];
        }
        if (array_key_exists('msg', $params)) {
            $this->msg = $params['msg'];
        }
    }

    public function render($e)
    {
        $this->code = $e->code ?? 500;
        $this->msg = $e->msg ?? $e->message;

        // 不成功时记录日志文件
        $params = post();
        logger()->error($this->msg, empty($params) ? get() : $params);

        // 发送钉钉群消息
        $msgStr = 'code:' . $this->code . ',msg:' . $this->msg;
        if ($e instanceof \Exception) {
            $msgStr .= ',file:' . $e->getFile() . ',line:' . $e->getLine();
        }
        DingDing::sendErrorMsg($msgStr, $params);

        return [
            'code' => $this->code,
            'result' => $this->msg,
        ];
    }
}
